package com.bright.tactiviti.process.definition;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;
import java.util.List;

/**
 * 流程定义笔记
 */
@SpringBootTest
public class ProcessDefinitionNote {
    @Autowired
    private RepositoryService repositoryService;

    /**
     * 查询流程定义
     * 操作对应数据表
     * ACT_RE_PROCDEF
     */

    @Test
    public void processDefinitionQuery(){
        //获取 流程定义 查询器
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        List<ProcessDefinition> processDefinitions = processDefinitionQuery
                .list();
        processDefinitions.forEach(definition -> {
            System.out.println("流程部署ID：" + definition.getDeploymentId());
            System.out.println("流程定义ID: " + definition.getId());
        });
    }
    /**
     * 查询所有流程的最新版本
     *
     * 操作对应数据表
     * ACT_RE_PROCDEF
     */
    @Test
    public void processDefinitionQueryFinal(){
        //获取 流程定义 查询器
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();

        List<ProcessDefinition> processDefinitions = processDefinitionQuery.latestVersion().list();

        processDefinitions.forEach(definition -> {
            System.out.println("流程部署id：" + definition.getDeploymentId());
            System.out.println("流程定义id：" + definition.getId());
        });
    }
    /**
     * 读取流程图文件
     * 把流程图的png读取到硬盘的某个文件里
     */
    @Test
    public void processDefinitionQueryView() throws IOException {
        //视图存档地址路径
        String  viewPath = System.getProperty("user.dir") + "/view";

        //判断文件是否存在
        File folder = new File(viewPath);
        if(!folder.exists()){
            //不存在则创建一个
            folder.mkdir();
        }

        //这里可以通过查询到资源文件，这里是测试，暂时写死
        viewPath += "/LeaveProcess.png";
        System.out.println(viewPath);

        //创建文件，给出相对应的Path
        File file = new File(viewPath);

        //流程定义ID
        String processDefinitionId = "LeaveProcess:1:4";

        try (InputStream inputStream = repositoryService.getProcessDiagram(processDefinitionId);
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {
            //开始写入文件
            int len;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf)) != -1){
                outputStream.write(buf,0,len);
                outputStream.flush();
            }
            System.out.println("视图读取完成");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("视图读取失败");
        }

    }

}
